package com.shicheng.mediaplayer.media;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.SeekBar;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by SHICHENG
 * <p>
 * Time on 2021/11/08
 */
public class MediaManager {

    private static MediaManagerBuilder mediaManagerBuilder;

    public static MediaManagerBuilder builder() {
        mediaManagerBuilder = new MediaManagerBuilder();
        return mediaManagerBuilder;
    }

    public static void start(){
        mediaManagerBuilder.start();
    }

    public static boolean isPlaying(){
        if (mediaManagerBuilder!=null){
            return mediaManagerBuilder.isPlaying();
        }
        return false;
    }

    public static void stop(){
        if (mediaManagerBuilder!=null){
            mediaManagerBuilder.stop();
        }
    }

    public static void pause(){
        if (mediaManagerBuilder!=null){
            mediaManagerBuilder.pause();
        }
    }

    public static void resume(){
        if (mediaManagerBuilder!=null){
            mediaManagerBuilder.resume();
        }
    }
    public static void removeAll(){
        if (mediaManagerBuilder!=null){
            mediaManagerBuilder.removeAll();
        }
    }

    public static class MediaManagerBuilder{

        public final String TAG = this.getClass().getSimpleName();
        private Handler handler = new Handler();
        private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。

        private Context context;
        private MediaConfig config;
        private MediaCallBack mediaListener;
        private MediaPlayer mediaPlayer;
        private boolean DEBUG = false;
        private SimpleDateFormat format;
        private Timer timer;
        private TimerTask timerTask;
        private SeekBar seekBar;

        private MediaManagerBuilder() {
            this.config = new MediaConfig();
            this.mediaPlayer = new MediaPlayer();
            this.format = new SimpleDateFormat("mm:ss");
        }

        /**
         * 当前Activity的上下文
         *
         * @param context
         * @return
         */

        public MediaManagerBuilder setContext(Context context){
            this.context = context;
            return this;
        }

        /**
         * 设置MediaPlayer Url链接
         *
         * @param url
         * @return
         */
        public MediaManagerBuilder setUrl(String url){
            this.config.url = url;
            return this;
        }

        /**
         * 设置播放进度监听回调
         *
         * @param mediaListener
         * @return
         */
        public MediaManagerBuilder setMediaListener(MediaCallBack mediaListener){
            this.mediaListener = mediaListener;
            return this;
        }

        /**
         * 设置是否是debug
         *
         * @param b
         * @return
         */
        public MediaManagerBuilder setDebugModel(boolean b){
            this.DEBUG = b;
            return this;
        }

        /**
         * 设置进度条
         */
        public MediaManagerBuilder setProgressSeek(SeekBar seek){
            this.seekBar = seek;
            return this;
        }


        /**
         * 初始化MediaPlayer
         */

        public MediaManagerBuilder build(){
            Uri uri = Uri.parse(config.url);
            //播放器不能为空
            if (mediaPlayer!=null){
                //如果是正在播放的状态 需要暂停上一个
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.stop();
                }
                //重置播放器
                mediaPlayer.release();
            }
            //创建新的播放器
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(config.url); //指定音频文件的路径
                mediaPlayer.prepare();//让mediaplayer进入准备状态
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        if (seekBar!=null){
                            seekBar.setMax(mediaPlayer.getDuration());
                        }
                        mediaListener.prepare(mediaPlayer.getDuration(),format.format(mediaPlayer.getDuration()) + "");
                    }
                });
                // 监听音频播放完的代码，实现音频的自动循环播放
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer arg0) {
                        mediaListener.end();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
            timerTask = new TimerTask() {

                Runnable updateUI = new Runnable() {
                    @Override
                    public void run() {
                        if (mediaPlayer != null && mediaPlayer.getCurrentPosition() != -1) {
                            mediaListener.progress(mediaPlayer.getCurrentPosition(), mediaPlayer.getDuration());
                        }
                    }
                };

                @Override
                public void run() {
                    if (!isSeekBarChanging) {
                        if (seekBar!=null){
                            seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        }
                        handler.post(updateUI);
                    }

                }
            };
            if (seekBar!=null){
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                        isSeekBarChanging = true;
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        isSeekBarChanging = false;
                        mediaPlayer.seekTo(seekBar.getProgress());
                    }
                });
            }
            return this;
        }


        /**
         * 开始播放
         */
        private void start(){
            //开始播放
            mediaPlayer.start();
            if (seekBar!=null){
                mediaPlayer.seekTo(seekBar.getProgress());
            }
            if (DEBUG){
                Log.i(TAG, "start: media start");
            }
            //监听播放时回调函数
            timer = new Timer();
            timer.schedule(timerTask,0,50);
        }

        /**
         * 停止播放
         */
        private void stop(){
            //播放器不能为空  为空终止
            if (mediaPlayer == null){
                return;
            }
            mediaPlayer.stop();
            if (DEBUG){
                Log.i(TAG, "start: media stop");
            }
        }

        /**
         * 暂停播放
         */
        private void pause(){
            //播放器不能为空  为空终止
            if (mediaPlayer == null){
                return;
            }
            mediaPlayer.pause();
            if (DEBUG){
                Log.i(TAG, "start: media pause");
            }
        }

        /**
         * 继续播放
         */
        private void resume(){
            //播放器不能为空  为空终止
            if (mediaPlayer == null){
                return;
            }
            mediaPlayer.start();
            if (DEBUG){
                Log.i(TAG, "start: media resume");
            }
        }

        /**
         * 是否是播放中
         */
        private boolean isPlaying(){
            if (mediaPlayer!=null){
                return mediaPlayer.isPlaying();
            }
            return false;
        }

        /**
         * 移除所有 清除内存
         */
        public void removeAll(){
            isSeekBarChanging = true;
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }



    }




}
